/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.ctop.modules.job.service;

import java.util.List;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ctop.common.persistence.Page;
import com.ctop.common.service.CrudService;
import com.ctop.common.utils.StringUtils;
import com.ctop.modules.job.entity.ScheduleJob;
import com.ctop.modules.job.utils.ScheduleUtils;
import com.ctop.modules.consts.Consts;
import com.ctop.modules.job.dao.ScheduleJobDao;

/**
 * 定时任务日志Service
 * @author linbc
 * @version 2017-12-19
 */
@Service
@Transactional(readOnly = true)
public class ScheduleJobService extends CrudService<ScheduleJobDao, ScheduleJob> {

	@Autowired
    private Scheduler ctopScheduler;
	
	public ScheduleJob get(String id) {
		return super.get(id);
	}
	
	public List<ScheduleJob> findList(ScheduleJob scheduleJob) {
		return super.findList(scheduleJob);
	}
	
	public Page<ScheduleJob> findPage(Page<ScheduleJob> page, ScheduleJob scheduleJob) {
		return super.findPage(page, scheduleJob);
	}
	
	@Transactional(readOnly = false)
	public void save(ScheduleJob scheduleJob) {
		String id = scheduleJob.getId();
		super.save(scheduleJob);
		if (StringUtils.isBlank(id)){//新增任务
			ScheduleUtils.createScheduleJob(ctopScheduler, scheduleJob);
		}else{//修改任务
			ScheduleUtils.updateScheduleJob(ctopScheduler, scheduleJob);
		}
		
	}
	
	@Transactional(readOnly = false)
	public void delete(ScheduleJob scheduleJob) {
		super.delete(scheduleJob);
		ScheduleUtils.deleteScheduleJob(ctopScheduler, scheduleJob.getId());
	}
	
	@Transactional(readOnly = false)
	public void pause(ScheduleJob scheduleJob) {
		ScheduleUtils.pauseJob(ctopScheduler, scheduleJob.getId());
		scheduleJob.setStatus(Consts.quartzConsts.PAUSE);
		dao.updateStatus(scheduleJob);
	}
	
	@Transactional(readOnly = false)
	public void resume(ScheduleJob scheduleJob) {
		ScheduleUtils.resumeJob(ctopScheduler, scheduleJob.getId());
		scheduleJob.setStatus(Consts.quartzConsts.NORMAL);
		dao.updateStatus(scheduleJob);
	}
	
	@Transactional(readOnly = false)
	public void run(ScheduleJob scheduleJob) {
		ScheduleUtils.run(ctopScheduler, scheduleJob);
	}
	
}